#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" pyCSS unit tests

To run the tests, cd to pycss root directory then type:
PYTHONPATH=.. python pycss/tests/tests.py
"""

import os.path
import unittest
import urllib

from pycss import pycss


class TestDefaultStylesheet(unittest.TestCase):

    def setUp(self):
        """Load and parse default stylesheet for HTML 4
        
        see http://www.w3.org/TR/CSS2/sample.html
        """
        path = os.path.dirname(__file__)
        filepath = os.path.join(path, 'default_stylesheet_html4.css')
        self.result = pycss.parser.parseFile(filepath)

    def testParsedToTheEnd(self):
        """Check if the stylesheet has been parsed to the end
        """
        self.assertEqual(len(self.result), 158);
        self.assertEqual(self.result[-1], 'invert');
        
    def testSelectorGroup(self):
        """Check if the SelectorGroup parser works as intended
        """
        selector_group = self.result[0]
        self.assertEqual(len(selector_group.selectors), 27)
        self.assertEqual(selector_group[-1], 'pre')


import functools

def build_tests(cls):
    template_method = getattr(cls, '_test_template')
    values = map(lambda x: str(x + 1).zfill(3), range(cls.max_index))
    for value in values:
        def gen_method(value):
            @functools.wraps(template_method)
            def wrapper(self):
                return template_method(self, value)
            wrapper.__name__ = 'testCSSZenGarden%s' % value
            wrapper.__doc__ = """Test CSSZenGarden CSS file #%s""" % value
            return wrapper
        new_method = gen_method(value)
        setattr(cls, new_method.__name__, new_method)
    delattr(cls, '_test_template')
    return cls


@build_tests
class TestCSSZenGarden(unittest.TestCase):
    """Test against all CSS files found on CSSZenGarden website
    
    The CSS files have already been downloaded and saved into the zencssgarden
    subdirectory. Test methods for each file are auto-magically generated by the 
    class decorator.
    
    Set max_index class attribute to the number of CSS files you want to test.
    Advice: start with 1 and increment the value until all CSS files have been
    tested (there are currently 213 of them).
    """
    
    max_index = 1  # upto 213
    
    def _test_template(self, index):
        """The template test method.
        
        This method is auto-magically duplicated by the class decorator, so that
        each CSS file to be tested has its own test method. This might ease 
        debugging.
        
        As each CSS file is different, the test method does nothing but assert 
        the parser works without raising any exception.
        """
        path = os.path.dirname(__file__)
        filepath = os.path.join(path, 'csszengarden', '%s.css' % index)
        pycss.parser.parseFile(filepath)


if __name__ == '__main__':
    unittest.main()

